package com.ihunanren.biz.weixin.ao.impl;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Strings.isNullOrEmpty;

import java.sql.SQLException;

import org.apache.commons.lang.builder.ToStringBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.google.common.base.Throwables;
import com.ihunanren.biz.common.HnrResourceLoader;
import com.ihunanren.biz.function.service.WeixinServiceAdapter;
import com.ihunanren.biz.result.Result;
import com.ihunanren.biz.result.ResultSupport;
import com.ihunanren.biz.weixin.WeixinMsgHelper;
import com.ihunanren.biz.weixin.ao.IWeixinAO;
import com.ihunanren.biz.weixin.domain.WeixinEventMsg;
import com.ihunanren.biz.weixin.domain.WeixinMsg;
import com.ihunanren.biz.weixin.domain.WeixinTextMsg;
import com.ihunanren.common.Pair;
import com.ihunanren.common.auth.SHA1;
import com.ihunanren.dao.WeixinMsgPojo;
import com.ihunanren.dao.WeixinMsgType;
import com.ihunanren.dao.pojo.AppUserDO;
import com.ihunanren.dao.weixin.IAppUserDao;
import com.ihunanren.dao.weixin.IWeixinMsgDao;

/**
 * @author kalman03
 */
public class WeixinAO implements IWeixinAO {
	private final static Logger log = LoggerFactory.getLogger(WeixinAO.class);

	@Autowired
	private IAppUserDao appUserDao;
	@Autowired
	private IWeixinMsgDao weixinMsgDao;
	

	@Override
	public boolean isWeixinAuthRequest(String nonce, String timestamp,
			String weixinSignature, String id) {
		
		checkArgument(!isNullOrEmpty(nonce) && !isNullOrEmpty(timestamp)
				&& !isNullOrEmpty(weixinSignature) && !isNullOrEmpty(id),
				"nonce or timestamp or weixinSignature or id is null");
		try {
			//AppUserDO appUser = appUserDao.getAppUserById(Long.parseLong(id));
			String token = "weixin";//根据用户取，FIXME appUser.getWeixinToken();

			String signature = SHA1.encrypt(token, nonce, timestamp);

			return signature.equalsIgnoreCase(weixinSignature);
		} catch (Exception e) {
			log.error("Weixin first signature catch a exception.", e);
		}
		return false;
	}

	@Override
	public boolean saveWeixinReplyMsg(Pair<? extends WeixinMsg, WeixinMsgType> pair,long id) {
		checkArgument(id > 0,"id can't be null.");
		try {
			//springEmail.send("kalman03@163.com","");
			Pair<? extends WeixinMsgPojo, WeixinMsgType> pojo = WeixinMsgHelper.toWeixinNormalMsgDO(pair, id);
			return weixinMsgDao.insertWeixinNormalMsg(pojo);
		} catch (Exception e) {
			log.error("saveWeixinReplyMsg catch a exception.", e);
		}
		return false;
	}

	@Override
	public Result getReplyMsgResponse(Pair<? extends WeixinMsg, WeixinMsgType> pair,long id) {
		Result result = new ResultSupport(false);
		try {
			AppUserDO appUserDO = getAppUserDO(id);
			System.out.println(ToStringBuilder.reflectionToString(pair.fst));
			
			if(pair.snd == WeixinMsgType.TEXT){
				String textMsg = HnrResourceLoader.getResoureceAsString("wx_msg_text.xml");
				WeixinTextMsg msg = (WeixinTextMsg) pair.fst;
				
				String reply = getReply(msg.getContent(),appUserDO);
				
				if(isNullOrEmpty(reply)){
					//FIXME 这里可进行一些其他的操作
					return result;
				}
				String str = String.format(textMsg, msg.getFromUserName(),msg.getToUserName(),
						String.valueOf(System.currentTimeMillis() / 1000),
						WeixinMsgType.TEXT.getValue(),reply, "0");
				result.setSuccess(true);
				result.setDefaultModel(str);
			}else if(pair.snd == WeixinMsgType.IMAGE){
				//String textMsg = HnrResourceLoader.getResoureceAsString("msg_text.xml");
				
			}else if(pair.snd == WeixinMsgType.LINK){
				//String textMsg = HnrResourceLoader.getResoureceAsString("msg_text.xml");
				
			}else if(pair.snd == WeixinMsgType.EVENT){
				String textMsg = HnrResourceLoader.getResoureceAsString("wx_msg_text.xml");
				WeixinEventMsg msg = (WeixinEventMsg) pair.fst;
				String str = String.format(textMsg, msg.getFromUserName(),
						msg.getToUserName(),
						String.valueOf(System.currentTimeMillis() / 1000),
						WeixinMsgType.TEXT.getValue(),
								"欢迎你关注湖南人微信公众账号！\n\n湖南人公众账号的责任编辑叫小白，有任何问题可以叫小白帮你解决哦！\n\n当然，欢迎你的爆料，让我们的生活更加多姿多彩！\n\n回复m开始体验湖南人提供的各种生活服务吧。",
								"0");
				result.setSuccess(true);
				result.setDefaultModel(str);
			}
		} catch (Exception e) {
			log.error("getReplayMsgResponse catch a exception.",e);
		}
		return result;
	}
	
	
	private AppUserDO getAppUserDO(long id) {
		AppUserDO appUser = null;
		try {
			appUser = appUserDao.getAppUserById(id);
		} catch (SQLException e) {
			Throwables.propagate(e);
		}
//		if (appUser == null)
//			throw new RuntimeException("user not found in db.");
		return appUser;
	}
	
	private String getReply(String input,AppUserDO appUser){
		WeixinServiceAdapter adapter = new WeixinServiceAdapter(input, appUser);
		return adapter.getResponse();
	}
}
